
//
//  LGRefundApplyVC.m
//  LuxuryGoods
//
//  Created by DCQ on 2018/7/24.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "LGRefundApplyVC.h"
#import "AllOrdersListViewController.h"
#import "UserInfoModel.h"
#import "OrderListModel.h"
#import "LGImageManagerIO.h"
#import "OrderGoodsImgCell.h"
#import "LGApplyRefundWhyCell.h"
#import "LGApplyRefundAmountCell.h"
#import "LGApplyRefundInstructionsCell.h"
#import "OrderGoodsServiceCell.h"
#import "LGApplyRefundCredentialsCell.h"
#import "GSPickerView.h"
#import "TZImagePickerController.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "IdOrMteDetailModel.h"
#import "IdAndMaOrderListViewController.h"
#import "MessageListViewController.h"


NSString * const    RefundApplyerviceGoodsImgCellIdentifierIdentifier = @"RefundApplyerviceGoodsImgCellIdentifierIdentifier";
NSString * const   RefundApplyerviceCellIdentifier = @"RefundApplyerviceCellIdentifier";

NSString * const   LGApplyRefundWhyCellIdentifier = @"LGApplyRefundWhyCellIdentifier";
NSString * const   LGApplyRefundAmountCellIdentifier = @"LGApplyRefundAmountCellIdentifier";
NSString * const   LGApplyRefundInstructionsCellIdentifier = @"LGApplyRefundInstructionsCellIdentifier";
NSString * const   LGApplyRefundCredentialsCellIdentifier  = @"LGApplyRefundCredentialsCellIdentifier";

@interface LGRefundApplyVC ()<TZImagePickerControllerDelegate>
@property(nonatomic,strong)NSNumber * orderId ;
@property(nonatomic,copy)NSString *refund_desc;//退款原因
@property(nonatomic,copy)NSString *refund_price;//退款金额
@property(nonatomic,copy)NSString *refund_explain;//退款说明
@property(nonatomic,copy)NSString *refund_img;//凭证图片 多个,隔开
@property(nonatomic, strong) OrderInfoModel * model;
@property(nonatomic, strong) IdOrMteInfoModel * infoModel;
@property (nonatomic,strong)GSPickerView *pickerView;
@property(nonatomic, strong) NSMutableArray *selectedPhotos;//图片数据
@property(nonatomic, strong) NSMutableArray *selectedAssets;
@end

@implementation LGRefundApplyVC



- (instancetype)initWithOrderModel:(OrderInfoModel *)orderModel{
    self = [super init];
    if (self) {
        self.model = orderModel;
        self.orderId = orderModel.order_id;
    }
    return self;
}
- (instancetype)initWithInfoModel:(IdOrMteInfoModel *)infoModel{
    
    self = [super init];
    if (self) {
        self.infoModel = infoModel;
        self.orderId = infoModel.order_id;
    }
    return self;
}
- (GSPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[GSPickerView alloc]initWithFrame:self.view.bounds];
        _pickerView.buttonColor = UIColorFromRGB(0x49BAFF);
        _pickerView.titleColor = UIColorFromRGB(0x000000);
        _pickerView.titleBgColor = UIColorFromRGB(0xF6F6F6);
    }
    return _pickerView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItemTitle:@"申请退款"];
    [self setupBottomView];
}

- (void)setupBottomView{
    CGFloat bottomHeight = 50;
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height-bottomHeight, self.view.frame.size.width, bottomHeight)];
    [bottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bottomView];
    NSString * btnTitle = @"提交";
  
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:btnTitle forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(20, 5, self.view.frame.size.width -40, bottomHeight- 10)];
    btn.layer.cornerRadius = (bottomHeight- 10)/2;
    btn.layer.masksToBounds =  YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bottomView addSubview:btn];
    UIImage * bgImg = [LGImageManagerIO createGradualColorImage:btn.size startColor:UIColorFromRGB(0xE1CFA9) endColor:UIColorFromRGB(0xC1B284)];
    [btn setBackgroundImage:bgImg forState:UIControlStateNormal];
}

- (void)btAction:(id)sender{
    
    [self submitRefund];
}

- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsImgCell  class]) bundle:nil] forCellReuseIdentifier:RefundApplyerviceGoodsImgCellIdentifierIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsServiceCell  class]) bundle:nil] forCellReuseIdentifier:RefundApplyerviceCellIdentifier]; 
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LGApplyRefundWhyCell  class]) bundle:nil] forCellReuseIdentifier:LGApplyRefundWhyCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LGApplyRefundAmountCell  class]) bundle:nil] forCellReuseIdentifier:LGApplyRefundAmountCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LGApplyRefundInstructionsCell  class]) bundle:nil] forCellReuseIdentifier:LGApplyRefundInstructionsCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LGApplyRefundCredentialsCell  class]) bundle:nil] forCellReuseIdentifier:LGApplyRefundCredentialsCellIdentifier];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger rows =  0;
    if (section == 0) {

        rows = 2;
    }else{
        rows = 5;
    }
    return rows;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 0;
    if (indexPath.section == 0) {
        height = 100;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0 ) {
            height = 50;
        }else if (indexPath.row == 1){
            height = 50;
        }else if (indexPath.row == 2){
            height = 50;
        }else if (indexPath.row == 3){
            height = 110;
        }else if (indexPath.row ==  4){
            height = 76;
        }
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.section == 0) {
        OrderGoodsImgCell * tempCell = [tableView dequeueReusableCellWithIdentifier:RefundApplyerviceGoodsImgCellIdentifierIdentifier];
        if (self.model) {
             [tempCell setupADdressData:self.model.goods_item[indexPath.row]];
        }else if (self.infoModel){
             [tempCell setupADdressData:self.infoModel.goods_item[indexPath.row]];
        }
      
        cell = tempCell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0 ) {
            LGApplyRefundWhyCell * tempCell = [tableView dequeueReusableCellWithIdentifier:LGApplyRefundWhyCellIdentifier];
            [tempCell setupRefund:self.refund_desc];
            
            cell = tempCell;
        }else if (indexPath.row == 1){
            LGApplyRefundAmountCell * tempCell = [tableView dequeueReusableCellWithIdentifier:LGApplyRefundAmountCellIdentifier];
              if (self.model) {
                  [tempCell setupRefundAmount:self.model.pay_price];
                  
              }else if (self.infoModel){
                   [tempCell setupRefundAmount:self.infoModel.pay_price];
              }
            cell = tempCell;
        }else if (indexPath.row == 2){
            LGApplyRefundInstructionsCell * tempCell = [tableView dequeueReusableCellWithIdentifier:LGApplyRefundInstructionsCellIdentifier];
            tempCell.changeTFBlock = ^(NSString *tfText) {
                self.refund_explain = tfText;
            };
            cell = tempCell;
        }else if (indexPath.row == 3){
            LGApplyRefundCredentialsCell * tempCell = [tableView dequeueReusableCellWithIdentifier:LGApplyRefundCredentialsCellIdentifier];
            [tempCell setupselectedPhotos:self.selectedPhotos withSelectedAssets:self.selectedAssets];
            tempCell.selectedImgBlock = ^{
                [self pushImagePickerController];
            };
            cell = tempCell;
        }else if (indexPath.row ==  4){
            OrderGoodsServiceCell * tempCell = [tableView dequeueReusableCellWithIdentifier:RefundApplyerviceCellIdentifier];
            tempCell.serviceBlock = ^{
                //联系客服

            };
            cell = tempCell;
        }
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        [self showWhyView];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.001;
    height = 8;
    return height;
}

- (void)showWhyView{
    [self requestWhyData];
}

- (void)requestWhyData{
     NSDictionary * params = @{@"token":UserInfo.userToken};
    NSString * pathStr = @"";
    if ( self.infoModel) {
        pathStr = @"/Otherorder/getRefundDescList";
    }
    if ( self.model) {
        pathStr = @"/Order/getRefundDescList";
    }
    [[MainApi sharedInstance] postPath:pathStr params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        if (!error) {
            NSArray * data = responseObject[@"data"];
            [self showChoooseRefundList:data];
        }
        
    }];
    
}
- (void)showChoooseRefundList:(NSArray *)refundList{
    
    [self.pickerView appearWithTitle:@"请选择退款原因" pickerType:GSPickerTypeOneComponentPicker subTitles:refundList selectedStr:self.refund_desc  sureAction:^(NSInteger path, NSString *pathStr) {
        self.refund_desc  = pathStr;
        [self.tableView reloadData];
        
    } cancleAction:^{
        
    }];
    
}
#pragma mark ---


- (void)showAlertMsg:(NSString *)msg{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                   message:msg
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:nil];
    
    
    [alert addAction:defaultAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma makr-----

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    
    // 1.设置目前已经选中的图片数组
    imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.circleCropRadius = 100;
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    //imagePickerVc.allowPreview = NO;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    [imagePickerVc setNaviBgColor:TOPCAIL_COLOR];
    [imagePickerVc setNaviTitleFont:[UIFont systemFontOfSize:15]];
    
    [imagePickerVc setDoneBtnTitleStr:@"确定"];
    
    [imagePickerVc setOKButtonTitleColorNormal:TOPCAIL_COLOR];
    [imagePickerVc setOKButtonTitleColorDisabled:[UIColor lightGrayColor]];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}



#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (self.selectedAssets) {
        [self.selectedAssets  removeAllObjects];
    }
    if (self.selectedPhotos) {
        [self.selectedPhotos removeAllObjects];
    }
    [self.selectedPhotos  addObjectsFromArray:photos];
    [self.selectedAssets  addObjectsFromArray: assets];
    
    
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
 
}
- (NSMutableArray *)selectedAssets{
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    return _selectedAssets;
}
- (NSMutableArray *)selectedPhotos{
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray array];
    }
    return _selectedPhotos;
}

#pragma mark ----

- (void)uploadImgV{
    NSDictionary * params = nil;
    NSMutableDictionary * fileDic = [NSMutableDictionary dictionary];
    for (int i =0;i<[self.selectedAssets count] ;i++) {
        UIImage * image = self.selectedPhotos[i];
        
        
        NSString * fileName = @"";
                if (iOS8Later) {

                    PHAsset * asset = self.selectedAssets[i];
                    fileName= asset.localIdentifier;
                    //            NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
                    //            fileName = ((PHAssetResource*)resources[0]).originalFilename;
                } else {
                    ALAsset * asset = self.selectedAssets[i];
                    fileName =  asset.defaultRepresentation.filename;

                }
        
        [fileDic setObject:image forKey: fileName];
    }
    if ([self.selectedAssets count] > 0) {
        [[MainApi sharedInstance] sendPostMutiUploadFilePath:@"Common/mutiUploadPic" params:params fileDic:fileDic  resultBlock:^(NSDictionary *responseObject, NSError *error) {
            NSDictionary * tempDic = responseObject[@"data"];
            if (tempDic[@"url"]) {
               self.refund_img = tempDic[@"url"];
            }
            [self submitRefundData];
        }];
        
    }
}

- (void)submitRefund{
    [self uploadImgV];
    
}

- (void)submitRefundData{
    if (self.model) {
        self.refund_price = self.model.pay_price;
    }else if (self.infoModel){
        self.refund_price = self.infoModel.pay_price;
    }
   
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if (!self.orderId || self.refund_desc||self.refund_price) {
        NSLog(@"提交信息不完整 不能提交");
        return;
    }
    [params  addEntriesFromDictionary:@{@"order_id":self.orderId,@"token":UserInfo.userToken,@"refund_desc":self.refund_desc,@"refund_price":self.refund_price}];
    
    if(self.refund_explain){
        [params addEntriesFromDictionary:@{@"refund_explain":self.refund_explain}];
    }
    if(self.refund_img){
          [params addEntriesFromDictionary:@{@"refund_img":self.refund_img}];
    }
 
    NSString * pathStr = @"";
    if ( self.infoModel) {
        pathStr = @"/Otherorder/refund";
    }
    if ( self.model) {
        pathStr = @"/Order/refund";
    }
    [[MainApi sharedInstance] postPath:pathStr params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        if (!error) {
            
            NSString * NotificationName = @"";
            
            if (self.fromVCType == RefundApplyFromVCType_Msg) {
                  NotificationName = @"UPDATE_MESSAGE_LIST";
            }else{
                if ( self.infoModel) {
                    NotificationName = @"UPDATE_IdAndMaOrder_LIST";
                }
                if ( self.model) {
                    NotificationName = @"UPDATE_ORDER_LIST";
                }
            }
           
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:nil];
            
            for (UIViewController * tempVC in self.navigationController.viewControllers) {
                if ([tempVC isKindOfClass:[AllOrdersListViewController class]]) {
                    [self.navigationController popToViewController:tempVC animated:YES];
                }
                if ([tempVC isKindOfClass:[IdAndMaOrderListViewController class]]) {
                    [self.navigationController popToViewController:tempVC animated:YES];
                }
                if ([tempVC isKindOfClass:[MessageListViewController class]]) {
                    [self.navigationController popToViewController:tempVC animated:YES];
                }
            }
            
        }
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
